from __future__ import annotations

import datetime as dt
from typing import Any, Dict, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from ..db import get_session
from ..models import RSSFeedItem
from ..services.rss_ingestor import rss_ingestor
from ..deps import require_admin


router = APIRouter(
    prefix="/rss",
    tags=["rss"],
    dependencies=[Depends(require_admin)],
)


class ManualFetchReq(BaseModel):
    feed: Optional[str] = Field(
        None,
        description="指定 feed 名称，仅刷新该源；为空时刷新所有源",
    )


class RSSItemResp(BaseModel):
    id: int
    source: str
    guid: str
    title: Optional[str] = None
    link: Optional[str] = None
    author: Optional[str] = None
    summary: Optional[str] = None
    published_at: Optional[dt.datetime] = None
    fetched_at: dt.datetime
    delivered: bool
    delivered_at: Optional[dt.datetime] = None

    class Config:
        orm_mode = True


@router.get("/feeds")
async def list_feeds() -> Dict[str, Any]:
    feeds = rss_ingestor.list_feeds()
    status = rss_ingestor.get_status()
    return {
        "enabled": rss_ingestor.enabled,
        "running": rss_ingestor.running,
        "feeds": feeds,
        "status": status,
    }


@router.post("/fetch")
async def manual_fetch(req: ManualFetchReq) -> Dict[str, Any]:
    if not rss_ingestor.enabled:
        raise HTTPException(status_code=400, detail="RSSHub 未启用，请先在配置中打开 RSSHUB_ENABLED")
    try:
        summary = await rss_ingestor.fetch_now(feed_name=req.feed)
    except ValueError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    return {
        "feeds": summary,
        "polled_at": rss_ingestor.get_status().get("last_polled_at"),
    }


@router.get("/items", response_model=List[RSSItemResp])
async def list_items(
    limit: int = Query(50, ge=1, le=200, description="返回条数"),
    source: Optional[str] = Query(None, description="过滤数据源名称"),
    delivered: Optional[bool] = Query(None, description="按投递状态过滤"),
    session: AsyncSession = Depends(get_session),
) -> List[RSSFeedItem]:
    stmt = select(RSSFeedItem).order_by(
        RSSFeedItem.published_at.desc().nulls_last(),
        RSSFeedItem.fetched_at.desc(),
    ).limit(limit)
    if source:
        stmt = stmt.where(RSSFeedItem.source == source)
    if delivered is not None:
        stmt = stmt.where(RSSFeedItem.delivered.is_(delivered))

    result = await session.execute(stmt)
    rows: List[RSSFeedItem] = list(result.scalars().all())
    return rows
